import 'package:account_book/common/dao/book_dao.dart';
import 'package:account_book/common/dao/category_dao.dart';
import 'package:account_book/common/entity/book.dart';
import 'package:account_book/common/entity/category.dart';
import 'package:account_book/common/utils/toast_util.dart';
import 'package:account_book/pages/category/index.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

class CategoryController extends GetxController {

  final state = CategoryState();

  final inputController = TextEditingController();

  @override
  void onReady() {
    super.onReady();
    _loadListData();
  }

  /// 加载数据
  void _loadListData () async {
    List<Category> list = await CategoryDao.instance.getListByType(state.type);
    state.listData.clear();
    if (list.isNotEmpty) {
      state.listData.addAll(list);
    }
  }

  /// 切换类型
  Future<void> switchType(int type) async {
    state.type = type + 1;
    _loadListData();
  }

  /// 保存
  Future<void> addCategory() async {
    final value = inputController.text;
    if (value.isEmpty) {
      ToastUtil.show("名称不能为空");
      return;
    }
    Category entity = Category(name: value);
    entity.type = state.type;
    entity.createDate = DateTime.now().toString();
    await CategoryDao.instance.insert(entity.toMap());
    _loadListData();
  }

  /// 更新
  Future<void> updateCategory(Category category) async {
    await CategoryDao.instance.update({"id": category.id}, category.toMap());
    _loadListData();
  }

  Future<void> removeCategory(int id) async {
    await CategoryDao.instance.removeById(id);
    _loadListData();
  }
}